//
//  DiscoverLisctViewController.m
//  TryShopping
//
//  Created by Mr.Lee on 2018/3/22.
//  Copyright © 2018年 RuiBen. All rights reserved.
//

#import "DiscoverLisctViewController.h"
#import "HouseholdDetailViewController.h"
#import "UIViewExt.h"

#import "HttpRequest.h"
#import "UIButton+WebCache.h"
#import "RDVTabBarController.h"

#import "HouseholdListCell.h"
#import "LoginViewController.h"
//#import "ToBindCompanyViewController.h"
#import "LoginCompanysViewController.h"
#import "DiscoverListModel.h"
#import "LXSegmentTitleView.h"
#import "LXScrollContentView.h"
#import "DiscoverLisctViewController.h"
#import "MJRefresh.h"
#import "TSFooterRefresh.h"                 // 刷新
#import "TSHeaderRefresh.h"
@interface DiscoverLisctViewController () <UITableViewDelegate, UITableViewDataSource>

@end

@implementation DiscoverLisctViewController 
{
//    MJRefreshHeaderView* _header;
//    MJRefreshFooterView* _footer;
//    CycleScrollViews *mainScorllView;
    NSMutableArray*modelArray;
    int pageNumber;
    NSString *pageSize;
    NSString *result;
    NSString*TotalCount;
    UITableView *table;
    UIView*noDataView;
    UIButton *userStatusBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    pageSize = @"20";
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.view.backgroundColor =[UIColor whiteColor];
    modelArray = [NSMutableArray array];
    [table removeFromSuperview];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, self.view.height) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];

    // 集成刷新控件
    [self setUpRefresh];
    // 网络请求
    [self requestData];
    

}


// 刷新
- (void)setUpRefresh {
    
    table.mj_header = [TSHeaderRefresh headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    
//    table.mj_footer= [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreProductList)];
    table.mj_footer = [TSFooterRefresh footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreProductList)];
    
}

//// 下拉刷新
- (void)headerRefresh {
    [self requestData];
}

-(void)requestData{
    pageNumber=1;
    [noDataView removeFromSuperview];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:pageSize forKey:@"pageSize"];
    [param setValue:self.dhTypeCode forKey:@"dhTypeCode"];
    
    NSLog(@"%@", param);
//    [MBProgressHUD showIndeterminateHudSub:@"" delay:30 view:self.view];
    [HttpRequest requestData:@"media/Household/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"====%@",severDataDict.dataDict);
        if (isSuccess) {
            [modelArray removeAllObjects];
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                for (NSDictionary* dicc in arrr ) {
                    
                    DiscoverListModel *model =[DiscoverListModel  mj_objectWithKeyValues:dicc];
                    [modelArray addObject:model];
                }
                
                if (arrr.count == 0) {
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                    if ([[user objectForKey:@"userStatus"] isEqualToString:@"W"]) {
                        
                    }else{
                        
                        noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, (ScreenHeight-64-49)/2-50, ScreenWidth, 80)];
                        [self.view addSubview:noDataView];
                        UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                        noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                        [noDataView addSubview:noImage];
                        UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                        noLabel.text=@"没有列表数据！";
                        noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                        noLabel.textAlignment=NSTextAlignmentCenter;
                        [noDataView addSubview:noLabel];
                        
                    }
                }
                
                [table.mj_header endRefreshing];
                [table reloadData];
                if (TotalCount.intValue < pageSize.intValue) {
                    [table.mj_footer endRefreshingWithNoMoreData];
                } else if(TotalCount.intValue > pageSize.intValue){
                    [table.mj_footer resetNoMoreData];
                }
            }else{
                [MBProgressHUD hideProgressHUDInternal:self.view];
                [table.mj_header endRefreshing];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    LoginViewController *loginVC=[[LoginViewController alloc] init];//2.0{9个参数 少2个}
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
            }
            
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            [table.mj_header endRefreshing];
        }
        
    }];
    
}

// 上拉刷新
- (void)loadMoreProductList{
    if (TotalCount.floatValue/pageSize.floatValue > pageNumber) {
        pageNumber++;
        NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
        NSString* tokenId = [user1 objectForKey:@"tokenId"];
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:tokenId forKey:@"tokenId"];
        [params setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
        [params setValue:pageSize forKey:@"pageSize"];
        [params setValue:self.dhTypeCode forKey:@"dhTypeCode"];
        [MBProgressHUD showIndeterminateHudSub:@"" delay:30 view:self.view];
        [HttpRequest requestData:@"media/Household/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [MBProgressHUD hideProgressHUDInternal:self.view];
                    NSMutableArray* arrr=[[NSMutableArray alloc]init];
                    arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                    for (NSDictionary* dicc in arrr ) {
                        DiscoverListModel *model =[DiscoverListModel  mj_objectWithKeyValues:dicc];
                        [modelArray addObject:model];
                    }
                    
                    
                    [table reloadData];
                    TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
                    if (TotalCount.intValue < pageSize.intValue) {
                        [table.mj_footer endRefreshingWithNoMoreData];
                    } else if(TotalCount.intValue >pageSize.intValue){
                        [table.mj_footer resetNoMoreData];
                    }
                }else {
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                }
                
            } else {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                [MBProgressHUD showTextHudSub:severDataDict.resultStr view:self.view];
            }
            
        }];
    }else{
        NSString *requestResultStr=@"没有更多数据了！";
        [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
        [table.mj_footer endRefreshingWithNoMoreData];
        
    }
    
//    [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0f];
//    NSLog(@"%@--->正在刷新", refreshView.class);
}
//
//- (void)doneWithView:(MJRefreshBaseView *)refreshView {
//    [table reloadData];
//    [refreshView endRefreshing];
//}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return modelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    HouseholdListCell* cell = (HouseholdListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"HouseholdListCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    DiscoverListModel *model = modelArray[indexPath.row];
    [cell.imageUrl.layer setCornerRadius:4.0];
    [cell.imageUrl.layer setBorderWidth:0.3];
    [cell.imageUrl.layer setMasksToBounds:YES];
    CGColorSpaceRef colorSpace2 = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref2 = CGColorCreate(colorSpace2,(CGFloat[]){ 0.93, 0.93, 0.93, 0.93 });
    [cell.imageUrl.layer setBorderColor:colorref2];//边框颜色
    
    [cell.imageUrl setImageWithURL:[NSURL URLWithString:model.imageUrlFull] placeholderImage:[UIImage imageNamed:@"zhengfangxing"]];
    
    cell.title.text =[NSString stringWithFormat:@"%@",  model.title];
    
    
    NSString* string =  model.pubTime;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    NSDate *destDate= [dateFormatter dateFromString:string];
    
    NSString *result1= nil;
    NSTimeInterval  timeInterval = [destDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    if (timeInterval < 60) {
        result1 = [NSString stringWithFormat:@"刚刚"];
    }else if((temp = timeInterval/60) <60){
        result1 = [NSString stringWithFormat:@"%ld分前",temp];
    }else if((temp = temp/60) <24){
        result1 = [NSString stringWithFormat:@"%ld小时前",temp];
    }else if((temp = temp/24) <30){
        result1 = [NSString stringWithFormat:@"%ld天前",temp];
    }else if((temp = temp/30) <12){
        result1 = [NSString stringWithFormat:@"%ld月前",temp];
    }else{
        temp = temp/12;
        result1 = [NSString stringWithFormat:@"%ld年前",temp];
    }
    cell.time.text =[NSString stringWithFormat:@"%@",  result1];
    cell.author.text =[NSString stringWithFormat:@"%@",  model.author];
    
    UIView *lineLabel1=[[UIView alloc] initWithFrame:CGRectMake(10, 100-0.50, ScreenWidth-20, 0.50)];
    lineLabel1.backgroundColor=qianhuiColor;
    [cell.contentView addSubview:lineLabel1];
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return  100;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DiscoverListModel *model = modelArray[indexPath.row];
    HouseholdDetailViewController *detailViewController = [[HouseholdDetailViewController alloc] init];
//    detailViewController.ImageUrl = model.imageUrlFull;
    detailViewController.fid = model.fid;
//    detailViewController.titleStr = model.title;
//    detailViewController.content = model.content;
    [self.navigationController pushViewController:detailViewController animated:YES];
}




@end
